package mqtt

import (
	"fmt"
	MQTT "github.com/eclipse/paho.mqtt.golang"

	"os"
)

type Msg struct{
	ClientId string
	ChannelId int
	Content []byte
}
var MsgCh = make(chan Msg,1000)

type Imf struct{
	Client string `json:"client"`
	Content string `json:"content"`
}

var MessageHandler1 MQTT.MessageHandler = func(client MQTT.Client, msg MQTT.Message) {

	var c = client.OptionsReader()
	clientId := c.ClientID()
	message := Msg{clientId,1,msg.Payload()}
	MsgCh<-message
}

var MessageHandler2 MQTT.MessageHandler = func(client MQTT.Client, msg MQTT.Message) {
	var c = client.OptionsReader()
	clientId := c.ClientID()


	message := Msg{clientId,2,msg.Payload()}
	MsgCh<-message
}

var r MQTT.MessageHandler = func(client MQTT.Client, msg MQTT.Message) {

	fmt.Println("来源不明！")

}

func NewOption(url string,clientId string) MQTT.Client{

	opts := MQTT.NewClientOptions().AddBroker(url)

	opts.SetClientID(clientId)
	opts.SetDefaultPublishHandler(r)


	client := MQTT.NewClient(opts)
	if token := client.Connect(); token.Wait() && token.Error() != nil {
		panic(token.Error())
	}
	return client
}


func SelfSubscribe(client MQTT.Client,topic string,qos byte,callback MQTT.MessageHandler){
	if token := client.Subscribe(topic, qos, callback); token.Wait() && token.Error() != nil {
		fmt.Println(token.Error())
		os.Exit(1)
	}

}

func SelfUnSubscribe(client MQTT.Client,topic string)  {
	if token := client.Unsubscribe(topic); token.Wait() && token.Error() != nil {
		fmt.Println(token.Error())
		os.Exit(1)
	}
}




